package array.simple;

import java.util.Stack;

/**
 * 删除字符串中的所有相邻重复项
 * 输入："abbaca"
 * 输出："ca"
 *
 * 链接：https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string
 */
public class RemoveAllAdjacentDuplicatesInString_1047 {


    public String removeDuplicates(String s) {

        int i = 0;
        Stack<Character> sc = new Stack<>();
        while(i < s.length()) {
            if (sc.isEmpty() || sc.peek() != s.charAt(i)) {
                sc.push(s.charAt(i++));
            } else {
                sc.pop();
                i++;
            }
        }
        char[] c = new char[sc.size()];
        for (int j = sc.size() - 1; !sc.isEmpty(); j--) {
            c[j] = sc.pop();
        }
        return String.valueOf(c);
    }

    public String removeDuplicatesOptimize(String s) {
        StringBuilder sb = new StringBuilder();
        int top = -1, i = 0;
        while (i < s.length()) {
            if (top == -1 || sb.charAt(top) != s.charAt(i)) {
                sb.append(s.charAt(i));
                top++;
            } else {
                sb.deleteCharAt(top);
                top--;
            }
            i++;
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        RemoveAllAdjacentDuplicatesInString_1047 raa = new RemoveAllAdjacentDuplicatesInString_1047();
        raa.removeDuplicates("abbaca");
        System.out.println(raa.removeDuplicatesOptimize("abbaca"));
    }
}
